package com.alibaba.moco.springboot;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.moco.util.BaseTypeUtil;
import com.alibaba.moco.util.PropertiesUtils;

import net.sf.json.JSONObject;

/**
 * 重新加载脚本comtroller
 * 
 * @author wb-lj240895
 */
@RestController
@EnableAutoConfiguration
@RequestMapping("/profile")
public class ProfileController {

    private static final String FIELD_CALLBACL_URL  = "callback_url";
    private static final String FIELD_USERNAME      = "username";
    private static final String ECODING_NAME        = "utf-8";

    private static final String FIELD_GITLAB_URL    = "gitlab_url";
    private static final String FIELD_GITLAB_TOKEN  = "gitlab_token";
    private static final String FIELD_GITLAB_NAME   = "gitlab_name";
    private static final String FIELD_GITLAB_ID     = "gitlab_id";
    private static final String FIELD_GITLAB_BRANCH = "gitlab_branch";

    private static final Logger logger              = LoggerFactory.getLogger(ProfileController.class);

    /**
     * 重新全量更新脚本
     * 
     * @return
     * @throws IOException
     */
    @RequestMapping("/reload")
    public String reloadScript() throws IOException {
        File file = new File(BaseTypeUtil.getClassPath() + "version.info");
        if (file.exists()) {
            FileUtils.writeStringToFile(file, "");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "SUCCESS");
        return jsonObject.toString();
    }

    /**
     * moco配置项
     * 
     * @param url 欢行地址
     * @param branch 使用的moco分支名
     * @param address redis地址
     * @param port redis端口
     * @param database redis数据库
     * @param pass redis密码
     * @param expire 超时时间
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("configs")
    public String mocoConfig(@RequestParam(value = FIELD_CALLBACL_URL, required = true) String callbackUrl,
                             @RequestParam(value = FIELD_GITLAB_URL, required = false) String gitlabUrl,
                             @RequestParam(value = FIELD_GITLAB_TOKEN, required = false) String token,
                             @RequestParam(value = FIELD_GITLAB_NAME, required = false) Integer projectName,
                             @RequestParam(value = FIELD_GITLAB_ID, required = false) String projectId,
                             @RequestParam(value = FIELD_GITLAB_BRANCH, required = false) String branch,
                             HttpSession session) throws UnsupportedEncodingException {
        if (StringUtils.isNotBlank(callbackUrl)) {
            session.setAttribute(FIELD_CALLBACL_URL, URLEncoder.encode(callbackUrl, ECODING_NAME));
            session.setAttribute(FIELD_USERNAME, URLEncoder.encode("郎心", ECODING_NAME));
            return "forward:/pages/index.html";
        }
        return "redirect:/pages/config.html";
    }

    @RequestMapping("info")
    public String configInfo(HttpSession session) {
        JSONObject json = new JSONObject();
        if (session != null) {
            Object callbackUrl = session.getAttribute(FIELD_CALLBACL_URL);
            Object username = session.getAttribute(FIELD_USERNAME);
            if (callbackUrl != null && username != null) {
                String url = String.valueOf(callbackUrl);
                String name = String.valueOf(username);
                json.put(FIELD_CALLBACL_URL, url);
                json.put(username, name);
                json.put("errno", 0);
            }
        }
        json.put("errno", -1);
        logger.info("profile/info | params: {}", json);
        return json.toString();
    }

    /**
     * 获取欢行地址
     * 
     * @return
     */
    @RequestMapping("url")
    public String happytripUrl(@CookieValue(name = FIELD_CALLBACL_URL) String callbackUrl) {
        if (StringUtils.isNotBlank(callbackUrl) && callbackUrl.startsWith("http://")) {
            JSONObject result = new JSONObject();
            result.put("url", callbackUrl);
            return result.toString();
        }

        String url = PropertiesUtils.getAttribute("hx_ip");
        String prot = PropertiesUtils.getAttribute("hx_prot");
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append("http://").append(url).append(":").append(prot).append("/");
        JSONObject result = new JSONObject();
        result.put("url", urlBuilder.toString());
        return result.toString();
    }
    /*
     * @RequestMapping("/aone") public String aone() throws IOException { File srcDir = new
     * File("/home/admin/moco/target/target/classes/script"); File destDir = new
     * File("/home/admin/moco/target/exploded/script"); FileUtils.copyDirectory(srcDir, destDir); JSONObject jsonObject
     * = new JSONObject(); jsonObject.put("status", "SUCCESS"); return jsonObject.toString(); }
     */
}
